package com_.dxy_test_.bio_.socket_;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class SocketClient { // 搭建客户端
    /**
     * class constant
     */
    static int POST = 44554;
    static String IP = "127.0.0.1";

    //Main也可以启动两个进程，模拟两个客户端，参考
    //https://blog.csdn.net/qq_44761854/article/details/122489698
    public static void main(String[] args) {
        SocketClient socketClient = new SocketClient();
        try {
            socketClient.openClient();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接失败");
        }
    }

    @SuppressWarnings("resource")
    public void openClient() throws IOException {
        Socket socket = new Socket(IP, POST);
        //连接成功后我们就建一个阻塞的IO来获取server广播的消息
        new ReadMsg(socket).start();
        System.out.println("客户端启动成功");
        PrintWriter pw = null;
        while (true) {
            //通过Scanner阻塞的接收键盘输入的信息发送到server
            pw = new PrintWriter(socket.getOutputStream());
            pw.println(new Scanner(System.in).next());
            pw.flush();
        }

    }

    /**
     * 异步监听收到的消息
     *
     * @author Allen 2017年7月19日
     *
     */
    class ReadMsg extends Thread {
        Socket socket;
        BufferedReader br;

        public ReadMsg(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = null;
                while (true) {
                    while ((line = br.readLine()) != null)
                        System.out.printf("%s\n",line);
                }

            } catch (SocketException e) {
                System.out.printf("%s\n","服务器断开了你的连接");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                clear();
            }
        }
        private void clear() {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            if (socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            this.interrupt();
        }
    }
}
